package com.example.excel.listener;

import cn.hutool.json.JSONObject;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.example.exception.BadRequestException;
import com.example.pojo.JobTableEntity;
import com.example.service.JobTableService;
import com.example.utils.SecurityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author
 * @description: 作业excel导入
 * @date 2022/3/17 8:20 PM
 */
public class JobTableDataListener extends AnalysisEventListener<Map<Integer, String>> {
	private static final int BATCH_COUNT = 50;
	private List<JobTableEntity> jobDos = ListUtils.newArrayListWithCapacity(BATCH_COUNT);
	private final JobTableService jobTableService;

	public JobTableDataListener(JobTableService jobTableService) {
		this.jobTableService = jobTableService;
	}

	@Override
	public void invoke(Map<Integer, String> o, AnalysisContext analysisContext) {
		UserDetails currentUser = SecurityUtils.getCurrentUser();
		JSONObject jsonObject = new JSONObject(new JSONObject(currentUser).get("user"));
		List<String> list = jsonObject.getJSONArray("jobs")
				.toList(JSONObject.class).stream()
				.map(i -> i.getStr("name")).collect(Collectors.toList());
		List<String> strings = Optional.of(list).orElse(ListUtils.newArrayList());
		if (!strings.contains(o.get(4))) {
			throw new BadRequestException("当前老师和excel课程名称不匹配");
		}
		Long currentUserId = SecurityUtils.getCurrentUserId();
		JobTableEntity jobTableEntity = new JobTableEntity();
		jobTableEntity.setStuNumber(o.get(0));
		jobTableEntity.setStuName(o.get(1));
		jobTableEntity.setSex(o.get(2));
		jobTableEntity.setProfession(o.get(3));
		jobTableEntity.setCourse(o.get(4));
		jobTableEntity.setUserId(currentUserId);
		for (Map.Entry<Integer, String> entry : o.entrySet()) {
			if (entry.getKey() > 4) {
				try {
					JobTableEntity clone = (JobTableEntity) jobTableEntity.clone();
					clone.setJobScore(new BigDecimal(entry.getValue()));
					jobDos.add(clone);
					if (jobDos.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						jobDos = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		// 保存
		saveData();
	}

	@Override
	public void onException(Exception exception, AnalysisContext context) throws Exception {
		super.onException(exception, context);
	}

	/**
	 * 保存到数据库
	 */
	public void saveData() {
		if (!jobDos.isEmpty()) {
			jobTableService.batchInsert(jobDos);
		}
	}
}

